<?php
namespace app\farm\model;

use app\BaseModel;
use think\facade\Db;

class CollageStart extends BaseModel
{
    //定义表名
    protected $name = 'lbfarm_v2_claim_collage_start';


    protected $append = [

        'surplus_num'

    ];


    /**
     * @param $value
     * @param $data
     * @功能说明:剩余人数
     * @author chenniang
     * @DataTime: 2022-08-19 10:05
     */
    public function getSurplusNumAttr($value,$data){

        if(isset($data['success_num'])&&isset($data['have_num'])){

            return ($data['success_num']-$data['have_num'])>=0?$data['success_num']-$data['have_num']:0;
        }

    }




    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:04
     * @功能说明:添加
     */
    public function dataAdd($data){

        $data['create_time'] = time();

        $res = $this->insert($data);

        return $res;

    }



    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:05
     * @功能说明:编辑
     */
    public function dataUpdate($dis,$data){

        $res = $this->where($dis)->update($data);

        return $res;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:06
     * @功能说明:列表
     */
    public function dataList($dis,$page){

        $data = $this->where($dis)->order('top desc,id desc')->paginate($page)->toArray();

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2022-07-01 15:33
     * @功能说明:
     */
    public function adminDataList($dis,$page=10){

        $data = $this->alias('a')
                ->join('lbfarm_claim b','a.claim_id = b.id','left')
                ->where($dis)
                ->field('a.*,b.title as claim_title')
                ->group('a.id')
                ->order('a.top desc,a.id')
                ->paginate($page)
                ->toArray();

        return $data;


    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:43
     * @功能说明:
     */
    public function dataInfo($dis){

        $data = $this->where($dis)->find();

        return !empty($data)?$data->toArray():[];

    }


    /**
     * @author chenniang
     * @DataTime: 2022-08-16 17:19
     * @功能说明:认养拼团商品
     */
    public function claimCollageLimit($claim_id,$limit=3,$user_id=0){

        $dis[] = ['end_time','>',time()];

        $dis[] = ['status','=',1];

        $dis[] = ['claim_id','=',$claim_id];

        $data = $this->where($dis)->order('id desc')->limit($limit)->select()->toArray();

        $user_model = new User();

        $collage_model = new CollageJoin();

        if(!empty($data)){

            foreach ($data as &$v){

                $v['user_info'] = $user_model->dataInfo(['id'=>$v['user_id']],'nickName,avatarUrl');
                //是否能参与拼团
                $v['can_join'] = $collage_model->collageCanJoin($user_id,$v['id']);

            }

        }

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2022-08-16 17:19
     * @功能说明:认养拼团商品
     */
    public function claimCollageList($dis,$page=10){

        $data = $this->where($dis)->order('id desc')->paginate($page)->toArray();

        $user_model = new User();

        $collage_model = new CollageJoin();

        if(!empty($data['data'])){

            foreach ($data['data'] as &$v){

                $v['user_info'] = $user_model->dataInfo(['id'=>$v['user_id']],'nickName,avatarUrl');

            }

        }

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2022-08-17 16:25
     * @功能说明：发起拼团
     */
    public function startCollage($order,$atv){

        $check = $this->startAtvCheck($order['user_id'],$atv['id']);

        if(!empty($check['code'])){

            return $check;
        }

        $insert = [

            'uniacid' => $order['uniacid'],

            'user_id' => $order['user_id'],

            'claim_id'=> $order['claim_id'],

            'end_time'=> time()+$atv['success_time']*60,

            'price'   => $atv['price'],

            'success_num'=> $atv['success_num'],

            'status'  => 0,

            'order_id'=> $order['id'],

            'atv_id'  => $atv['id'],

        ];

        $res = $this->dataAdd($insert);

        $id  = $this->getLastInsID();

        $data= $this->dataInfo(['id'=>$id]);

        return $data;
    }


    /**
     * @author chenniang
     * @DataTime: 2022-08-18 10:33
     * @功能说明:
     */
    public function getAtvInfo($atv_id,$claim_id){

        $data = $this->dataInfo(['id'=>$atv_id,'claim_id'=>$claim_id]);

        return $data;
    }


    /**
     * @author chenniang
     * @DataTime: 2022-08-18 11:45
     * @功能说明:活动回调
     */
    public function atvResult($order_id){

        $join_model = new CollageJoin();

        $data = $join_model->dataInfo(['order_id'=>$order_id]);

        if(!empty($data)){

            $this->dataUpdate(['order_id'=>$order_id,'status'=>0],['status'=>1]);

            $join_model->dataUpdate(['order_id'=>$order_id,'status'=>0],['status'=>1]);

            $this->where(['id'=>$data['id']])->update(['have_num'=>Db::Raw('have_num+1')]);

            $this->atvSuccess($data['start_id']);
        }

        return true;
    }


    /**
     * @author chenniang
     * @DataTime: 2022-08-18 11:47
     * @功能说明:拼团活动成功
     */
    public function atvSuccess($id){

        $data = $this->dataInfo(['id'=>$id,'status'=>1]);

        if(!empty($data)){

            $join_model = new CollageJoin();

            $count = $join_model->where(['start_id'=>$id,'status'=>1])->count();

            if($count>=$data['success_num']){

                $this->dataUpdate(['id'=>$id],['status'=>2,'success_times'=>time()]);

                $join_model->dataUpdate(['start_id'=>$id,'status'=>1],['status'=>2]);

            }

        }

        return true;
    }


    /**
     * @author chenniang
     * @DataTime: 2022-08-18 14:24
     * @功能说明:取消订单
     */
    public function cancelOrderAtvFail($order_id){

        $this->dataUpdate(['order_id'=>$order_id],['status'=>-1]);

        $this->where(['order_id'=>$order_id])->update(['have_order_num'=>Db::Raw('have_order_num+1')]);

        $join_model = new CollageJoin();

        $join_model->dataUpdate(['order_id'=>$order_id],['status'=>-1]);

        return true;

    }


    /**
     * @author chenniang
     * @DataTime: 2022-08-18 13:41
     * @功能说明:活动失效
     */
    public function initAtv($payConfig){

        $dis[] = ['end_time','<',time()];

        $dis[] = ['status','=',1];

        $list = $this->where($dis)->select()->toArray();

        $join_model = new CollageJoin();

        $order_model= new ClaimOrder();

        if(!empty($list)){

            foreach ($list as $value){

                Db::startTrans();

                $res = $this->dataUpdate(['id'=>$value['id']],['status'=>3]);

                if($res!=0){

                    $data = $join_model->where(['status'=>1,'start_id'=>$value['id']])->select()->toArray();

                    $join_model->dataUpdate(['status'=>1,'start_id'=>$value['id']],['status'=>3]);

                    if(!empty($data)){

                        foreach ($data as $v){

                            $order = $order_model->dataInfo(['id'=>$v['order_id'],'pay_type'=>2]);

                            if(!empty($order)){
                                //订单退款
                                $order_model->cancelOrder($order,2,$payConfig);

                            }

                        }

                    }

                }

                Db::commit();

            }

        }

        return true;

    }


    /**
     * @author chenniang
     * @DataTime: 2022-08-18 15:47
     * @功能说明:发起开团审核
     */
    public function startAtvCheck($user_id,$atv_id){

        $dis = [

            'user_id' => $user_id,

            'atv_id'  => $atv_id
        ];

        $count = $this->where($dis)->where('status','in',[0,1])->count();

        if(!empty($count)){

            return ['code'=>500,'msg'=>'你有正在进行中或未付款的团'];
        }

        $collage_model = new ClaimCollage();

        $data = $collage_model->dataInfo(['id'=>$atv_id,'status'=>1]);

        if(empty($data)||$data['end_time']<time()){

            return ['code'=>500,'msg'=>'活动已经结束'];

        }

        if($count>=$data['start_times']){

            return ['code'=>500,'msg'=>'超过发起拼团次数'];

        }

        return true;

    }


    /**
     * @param $user_id
     * @功能说明:获取用户正在发起中的拼团
     * @author chenniang
     * @DataTime: 2022-08-18 16:52
     */
    public function userCollageIngData($user_id,$claim_id){

        $data = $this->dataInfo(['user_id'=>$user_id,'status'=>1,'claim_id'=>$claim_id]);

        $collage_model = new CollageJoin();

        if(!empty($data)){

            $data['user_avatar'] = $collage_model->collageUserAvatar($data['id'],4);
        }

        return $data;
    }











}